<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
     <!-- 搜索 -->
     <el-row :gutter="20">
       <el-col :span="8">
        <el-input placeholder="请输入内容"  v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
       </el-col>
       <el-col :span="4">
         <el-button type="primary" @click="getSon('add')">添加用户</el-button>
       </el-col>
     </el-row>
     <!-- 表格 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="姓名" prop="username" align="center"></el-table-column>
        <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
        <el-table-column label="电话" prop="mobile" align="center"></el-table-column>
        <el-table-column label="角色" prop="role_name" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <!-- 作用域插槽 可通过scoped获取一行的所有内容 -->
          <template v-slot="scoped">
            <!-- {{ scoped.row }} -->
            <el-switch
              v-model="scoped.row.mg_state"
              @change="changeUser(scoped.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scoped" width="180px">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getSon('edit', scoped.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scoped.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
               <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="setUser(scoped.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码条 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
    <Dialog
      :dialogVisible="visible"
      :diaSonType="sonType"
      :diaEditForm="editForm"
      :userInfo="userInfo"
      :roles="roles"
      @changeVisible="parentChange"
      @setForm="parentSetform"
      @editForm="parentEditForm"
      @setUserRole="parentSetUserRole"
      @changeUseInfo="changeUseInfo"
    />
  </div>
</template>

<script>
import Dialog from '@/components/common/Dialog'
export default {
  data () {
    return {
      visible: false, // 弹出框的显示
      sonType: '',
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      flag: '',
      userList: [],
      total: 0,
      // 根据 id 找到的数据
      editForm: {},
      // setUser 当前的数据
      userInfo: {},
      // 所有角色列表
      roles: []
    }
  },
  components: {
    Dialog
  },
  created () {
    if (sessionStorage.getItem('pagesize')) {
      this.queryInfo.pagesize = Number(sessionStorage.getItem('pagesize'))
    } else {
      this.queryInfo.pagesize = 2
    }
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.err('获取数据失败')
      // console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变时触发
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
      sessionStorage.setItem('pagesize', newSize)
    },
    // 监听 pagenum 改变时触发
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async changeUser (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 改变 visible
    parentChange () {
      this.visible = false
    },
    // 处理 添加后的操作
    parentSetform () {
      this.queryInfo.pagenum = Math.floor(this.total / this.queryInfo.pagesize) + 1
      this.getUserList()
      this.visible = false
    },
    // 点击修改 发请求获取数据
    async getSon (type, id) {
      // console.log(type)
      this.sonType = type
      this.visible = true
      if (id) {
        const { data: res } = await this.$http.get(`users/${id}`)
        // console.log(res)
        this.editForm = res.data
      }
    },
    async parentEditForm (diaEditForm) {
      // console.log(diaEditForm)
      const { data: res } = await this.$http.put(`users/${diaEditForm.id}`, { email: diaEditForm.email, mobile: diaEditForm.mobile })
      if (res.meta.status !== 200) return this.$message.error('用户修改数据失败')
      // 关闭对话框
      this.visible = false
      // 更新数据
      this.getUserList()
      // 提示修改成功
      this.$message.success('修改成功！')
    },
    // 删除用户
    async removeUser (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err) // 捕获错误，并且renturn出去
      //  点击确认 返回 confirm
      // 点击取消 返回 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 分配角色
    async setUser (userInfo) {
      this.sonType = 'setUser'
      this.userInfo = userInfo
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roles = res.data
      this.visible = true
    },
    // 分配角色发送请求 通过emit事件处理子级的确定事件
    async parentSetUserRole (rid) {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败！')
      this.$message.success('分配角色成功！')
      this.visible = false
      // 重新获取用户列表
      this.getUserList()
    },
    // 模态框消失后 清空 UserInfo
    changeUseInfo () {
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>

</style>
